package com.keba.otp.server.api;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.bouncycastle.util.encoders.Hex;

import com.keba.otp.core.Company;
import com.keba.otp.core.User;
import com.keba.otp.crypto.Crypto;
import com.keba.otp.db.CompaniesDAO;
import com.keba.otp.db.DAOFactory;
import com.keba.otp.db.UsersDAO;

/**
 * Servlet implementation class LoginRequest
 */
public class LoginRequest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginRequest() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
/*	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}*/

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if (action != null) {
			if (action.equals("auth")) {
				login(request.getParameter("company"), request.getParameter("companypassw"), request.getParameter("user"), request.getParameter("passw"), request.getParameter("otp"), request, response);
			} 
		}
	}

	private void login(String company, String companypassw, String user, String pass,
			String otp, HttpServletRequest request, HttpServletResponse response) {
		DAOFactory daofactory = DAOFactory.getInstance(DAOFactory.MYSQL);
		UsersDAO usersdao = daofactory.getUsersDAO();
		DAOFactory daoFactory = DAOFactory.getInstance(DAOFactory.MYSQL);
		CompaniesDAO companiesDao = daoFactory.getCompaniesDAO();
		Company foundCompany;
/*		try{*/
			/*byte[] inBuff = company.getBytes("utf-8");
			byte[] outBuff = new byte[64];
			org.bouncycastle.crypto.digests.SHA512Digest digest = new org.bouncycastle.crypto.digests.SHA512Digest();
			digest.update(inBuff, 0, inBuff.length);
			int len = digest.doFinal(outBuff, 0);
			String hash = new String(Hex.encode(outBuff, 0, len));*/
		
		if ((foundCompany = companiesDao.getCompanyByName(company)) != null){
			if (foundCompany.getCompanyPass().equals(companypassw)){
				try {
					String decryptedUser = Crypto.performDecrypt(user, foundCompany.getCompanyKey());
					String decryptedPass = Crypto.performDecrypt(pass, foundCompany.getCompanyKey());
					String decryptedOTP = Crypto.performDecrypt(otp, foundCompany.getCompanyKey());
					byte[] inBuff = decryptedUser.getBytes("utf-8");
					byte[] outBuff = new byte[64];
					org.bouncycastle.crypto.digests.SHA512Digest digest = new org.bouncycastle.crypto.digests.SHA512Digest();
					digest.update(inBuff, 0, inBuff.length);
					int len = digest.doFinal(outBuff, 0);
					String hash = new String(Hex.encode(outBuff, 0, len));
					User foundUser = usersdao.getUserByHash(hash);
					if (foundUser != null) {
						byte[] key = foundUser.getKey();
						String username = Crypto.performDecrypt(foundUser.getName(), key);
						String password = Crypto.performDecrypt(foundUser.getPassw(), key);
						String foundOTP = foundUser.getOtp();
						String foundOTPCreationDate = foundUser.getOtpCreateDate();
						if (username.equals(decryptedUser) && password.equals(decryptedPass)) {
							if (foundOTP.equals(decryptedOTP)) {
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
								Date createDate = sdf.parse(foundOTPCreationDate);
								Date now = new Date();
								/*OutputStream out = response.getOutputStream();*/
								if (now.getTime() - createDate.getTime() < 90000) {
									response.getWriter().write("grant");
								}
									//out.write(1);
								/*} else
									out.write(0);
								out.flush();
								out.close();*/
								
							}
						}
					} else response.getWriter().write("no success");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		/*} catch (IOException e) {
			e.printStackTrace();
		} */
		
	}

}
